package com.lijia.ffmpeg4android.fragment;

import java.util.Date;
import java.util.UUID;

import com.actionbarsherlock.app.SherlockFragment;
import com.lijia.dennishucd.util.PictureUtils;
import com.lijia.ffmpeg4android.CrimeCameraActivity;
import com.lijia.ffmpeg4android.R;
import com.lijia.ffmpeg4android.model.Crime;
import com.lijia.ffmpeg4android.model.CrimeLab;
import com.lijia.ffmpeg4android.model.Photo;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

public class CrimeFragment extends SherlockFragment {
	public static final String TAG = "CrimeFragment";
	public static final String EXTRA_CRIME_ID = "com.activity.crime_id";
	public static final String DIALOG_FRAGMENT_TAG = "datePicker";
	public static final String DIALOG_IMAGE = "dialogImage";		
	public static final int REQUEST_DATE = 1;
	public static final int REQUEST_PHOTO = 2;
	public static final int REQUEST_CONTACT = 3;	
	
	private Crime mCrime;
	private EditText mEditText;
	private Button mDateButton;
	private CheckBox mSolvedCheckBox;
	
	private ImageButton mPhotoButton;
	private ImageView mPhotoView;
	
	private Button m_suspectButton;
	private	CrimeFragmentDelegate mDelegate;
	
	public interface CrimeFragmentDelegate {
		void onCrimeUpdated(Crime crime);
	}
	
	private CrimeFragment() {
		super();
	}
	
	public static CrimeFragment newInstance(UUID crimeId) {
		Bundle args = new Bundle();
		args.putSerializable(EXTRA_CRIME_ID, crimeId);
		CrimeFragment cf = new CrimeFragment();
		cf.setArguments(args);
		return cf;
	}	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		UUID crimeId = (UUID)this.getArguments().getSerializable(EXTRA_CRIME_ID);
		mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_crime, parent, false);
		this.mEditText = (EditText)v.findViewById(R.id.crime_title);
		this.mEditText.setText(mCrime.getTitle());
		this.mEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence c, int start, int before, int count) {
				mCrime.setTitle(c.toString());
			}
			
			@Override
			public void beforeTextChanged(CharSequence c, int start, int count, int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable c) {
				if(mDelegate != null) mDelegate.onCrimeUpdated(mCrime);
			}
		});
		
		mDateButton = (Button)v.findViewById(R.id.crime_date);		
		mDateButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				FragmentManager fManager = getActivity().getSupportFragmentManager();
				DatePickerFragment dpFragment = DatePickerFragment.newInstance(mCrime.getDate());
				dpFragment.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
				dpFragment.show(fManager, DIALOG_FRAGMENT_TAG);
			}
		});
		updateDateBtn();
		
		mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_sloved);
		mSolvedCheckBox.setChecked(mCrime.isSolved());
		mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mCrime.setSolved(isChecked);
				getActivity().setResult(1,null);
				if(mDelegate != null) mDelegate.onCrimeUpdated(mCrime);
			}
		});
		
		mPhotoButton = (ImageButton)v.findViewById(R.id.crime_imageButton);
		mPhotoButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent i = new Intent(getSherlockActivity(),CrimeCameraActivity.class);
				startActivityForResult(i, REQUEST_PHOTO);
			}
		});
		
		PackageManager pm = getSherlockActivity().getPackageManager();
		boolean hasAnyCamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) ||
							pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) ||
							Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD || 
							Camera.getNumberOfCameras() > 0;
		if (!hasAnyCamera) {
			mPhotoButton.setEnabled(false);
		}
		
		mPhotoView = (ImageView)v.findViewById(R.id.crime_imageView);
		mPhotoView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Photo p = mCrime.getPhoto();
				if (p == null) return;
				
				FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
				String filePath = getSherlockActivity().getFileStreamPath(p.getFilename()).getAbsolutePath();
				ImageFragment.newInstance(filePath).show(fm, DIALOG_IMAGE);
			}
		});
		
		Button reportButton = (Button)v.findViewById(R.id.crime_reportButton);
		reportButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent i = new Intent(Intent.ACTION_SEND);
				i.setType("text/plain");
				i.putExtra(Intent.EXTRA_TEXT, getCrimeReport());
				i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.crime_report_subject));
				i = Intent.createChooser(i, getString(R.string.send_report));
				startActivity(i);
			}
		});
		
		m_suspectButton = (Button)v.findViewById(R.id.crime_suspectButton);
		m_suspectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent i = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(i, REQUEST_CONTACT);
			}
		});
		
		if (mCrime.getSuspect() != null) {
			m_suspectButton.setText(mCrime.getSuspect());
		}
		
		return v;
	}
	

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if(resultCode != Activity.RESULT_OK) return;
		if(requestCode == REQUEST_DATE) {
			Date date = (Date)intent.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
			mCrime.setDate(date);
			updateDateBtn();
			if(mDelegate != null) mDelegate.onCrimeUpdated(mCrime);
		} else if (requestCode == REQUEST_PHOTO) {
			//create a new photo object and attach it to the crime
			String filename = intent.getStringExtra(CrimeCameraFragment.EXTRA_PHOTO_FILENAME);
			if (filename != null) {
				Log.i(TAG, "filename " + filename);
				Photo p = new Photo(filename);
				mCrime.setPhoto(p);
				showPhoto();
				if(mDelegate != null) mDelegate.onCrimeUpdated(mCrime);
				
				Log.i(TAG, "Crime: " + mCrime.getTitle() + " has a photo");
			}
		} else if (requestCode == REQUEST_CONTACT) {
			Uri contactUri = intent.getData();
			String[] queryFields = new String[] {
				ContactsContract.Contacts.DISPLAY_NAME
			};
			Cursor cursor = getSherlockActivity().getContentResolver().query(contactUri, queryFields, null, null, null);
			if (cursor.getCount() == 0) {
				cursor.close();
				return;
			}
			
			cursor.moveToFirst();
			String suspect = cursor.getString(0);
			mCrime.setSuspect(suspect);
			m_suspectButton.setText(suspect);
			cursor.close();
			if(mDelegate != null) mDelegate.onCrimeUpdated(mCrime);
		}
	}
	
	@Override
	public void onStart() {
		super.onStart();
		showPhoto();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		CrimeLab.get(getActivity()).saveCrimes();
	}	
	
	@Override
	public void onStop() {
		super.onStop();
		PictureUtils.cleanImageView(mPhotoView);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mDelegate = (CrimeFragmentDelegate)activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mDelegate = null;
	}

	private void updateDateBtn() {
		mDateButton.setText(mCrime.getDate().toString());		
	}
	
	private void showPhoto() {
		Photo p = mCrime.getPhoto();
		BitmapDrawable b = null;
		if (p != null) {
			String path = getActivity().getFileStreamPath(p.getFilename()).getAbsolutePath();
			b = PictureUtils.getScaledDrawable(getActivity(), path);
		}
		mPhotoView.setImageDrawable(b);
	}
	
	public String getCrimeReport() {
		String solvedStr = null;
		if (mCrime.isSolved()) {
			solvedStr = getString(R.string.crime_report_solved);
		} else {
			solvedStr = getString(R.string.crime_report_unsolved);
		}
		
		String dateFormat = "EEE, MMM dd";
		String dateStr = DateFormat.format(dateFormat, mCrime.getDate()).toString();
		
		String suspectStr = mCrime.getSuspect();
		if (suspectStr == null) {
			suspectStr = getString(R.string.crime_report_suspect);
		} else {
			suspectStr = getString(R.string.crime_report_no_suspect);
		}
		String report = getString(R.string.crime_report,mCrime.getTitle(),dateStr,solvedStr,suspectStr);
		return report;
	}
}
